package com.lyl.security.module.security.handler;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.lyl.security.common.result.ErrorCode;
import com.lyl.security.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.Luo
 * @date 2022-09-09 15:51
 * @desc 授权失败处理器
 */
@Slf4j
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.error("权限不足",accessDeniedException);
        ServletUtil.write(response, JSONUtil.toJsonStr(Result.build(ErrorCode.ACCESS_DENIED).setMsg(accessDeniedException.getMessage())), "application/json;charset=UTF-8");
    }
}
